//
//  CBadgeView.m
//  collection
//
//  Created by   张靖 on collection-10.
//  Copyright 2011年 collection. Inc.. All rights reserved.
//

#import "CBadgeView.h"

#define kTopMagin 3.0f
#define kLeftMagin 3.0f
#define kRightMagin 3.0f
#define kBottomMagin 3.0f

@interface CBadgeView ()

@property (nonatomic,retain) UIFont* textFont;

@end

@implementation CBadgeView
@synthesize badgeValue = _badgeValue;
@synthesize textFont = _textFont;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
	{
        self.backgroundColor = [UIColor clearColor];
		self.clipsToBounds = YES;
		
		self.badgeValue = @"";
		//self.textFont = [UIFont systemFontOfSize:13];
        self.textFont = [UIFont boldSystemFontOfSize:12];
    }
    return self;
}

- (id) initWithBadgeValue:(NSString*)badgeValue
{
	self = [self initWithFrame:CGRectNull];
	if (self)
	{
		self.badgeValue = badgeValue;
	}
	return self;
}

- (void) setBadgeValue:(NSString *)badgeValue
{
	if (badgeValue == nil)
	{
		badgeValue = @"";
	}

	NSString* s = [badgeValue copy];
	[_badgeValue release];
	_badgeValue = s;
	
	CGSize textSize = [badgeValue sizeWithFont:self.textFont];
	
	UIImage* l = [UIImage imageNamed:@"yuan_zuo.png"];
	UIImage* r = [UIImage imageNamed:@"yuan_you.png"];
	
	CGRect f = self.frame;
	f.size = CGSizeMake(MAX(kLeftMagin + textSize.width + kRightMagin, l.size.width + r.size.width), l.size.height);
	self.frame = f;
	
	[self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
	UIImage* l = [UIImage imageNamed:@"yuan_zuo.png"];
	UIImage* c = [UIImage imageNamed:@"yuan_zhong.png"];
	UIImage* r = [UIImage imageNamed:@"yuan_you.png"];
	
	CGRect bounds = self.bounds;
	float startX = 0.0f;
	[l drawAtPoint:CGPointMake(startX, 0)];
	startX += l.size.width;
	
	float w = bounds.size.width - l.size.width - r.size.width;
	if (w > 0)
	{
		[c drawInRect:CGRectMake(startX, 0, w, c.size.height)];
	}
	startX += w;
	
	[r drawAtPoint:CGPointMake(startX, 0)];
	
	if ([self.badgeValue length] > 0)
	{
		CGSize textSize = [self.badgeValue sizeWithFont:self.textFont];
		[[UIColor whiteColor] set];
		[self.badgeValue drawAtPoint:CGPointMake((bounds.size.width - textSize.width)/2, (bounds.size.height - textSize.height)/2) withFont:self.textFont];
	}
}

- (void)dealloc
{
	self.badgeValue = nil;
    [super dealloc];
}

@end
